package com.chuanjiabao.wisdom.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;

import com.chuanjiabao.wisdom.MainActivity;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.AddFamilyCallbackBean;
import com.chuanjiabao.wisdom.bean.FamilyDeatilCallbackBean;
import com.chuanjiabao.wisdom.bean.InviteCallbackBean;
import com.chuanjiabao.wisdom.bean.PhoneDto;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.bean.UpdateHeadCallBackBean;
import com.chuanjiabao.wisdom.bean.UpdateStatus;
import com.chuanjiabao.wisdom.databinding.ActivityAddFamilyBodyBinding;
import com.chuanjiabao.wisdom.greendao.gen.UpdateStatusDao;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.listener.RxObserver;
import com.chuanjiabao.wisdom.listener.UMShareListenerExt;
import com.chuanjiabao.wisdom.ui.ActivityStack;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.ui.view.DialogGLC;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.PhoneUtil;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.StringHelper;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.TimeUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.AddCompleteDialog;
import com.chuanjiabao.wisdom.util.dialog.ArriveDialog;
import com.chuanjiabao.wisdom.util.dialog.SelectSexDialog;
import com.chuanjiabao.wisdom.util.dialog.ShareDialog;
import com.chuanjiabao.wisdom.util.dialog.ShareFamilyFullDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.lzy.okgo.callback.StringCallback;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.carbs.android.gregorianlunarcalendar.library.data.ChineseCalendar;
import okhttp3.Call;
import okhttp3.Response;

import static com.chuanjiabao.wisdom.bean.Constants.REQUEST_CODE;

public class AddFamilyBodyActivity extends BaseActivity {

    private ActivityAddFamilyBodyBinding binding;
    String moduleFuncation, x, y, d_id;
    FamilyDeatilCallbackBean.DataBean.MembersBean membersBean;
    private SlimAdapter mAdapter;

    UpdateStatusDao updateStatusDao = FApplication.getInstance().getDaoSession().getUpdateStatusDao();

    //手机联系人
    private List<PhoneDto> phoneDtosSecond = new ArrayList<>();

    String d_relation = "",
            d_home_id = "",
            d_birthday_type = "",
            d_head_pic = "",
            d_birthday_str,
            d_name = "",
            d_birthday = "",
            d_alive = "",
            d_phone = "",
            d_sex = "",
            d_pic_upload = "0",
            d_user_id = "";

    boolean isOpen = true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_add_family_body);
        binding.setActivity(this);
        initList();
        initView();
    }

    private void initList() {
        LinearLayoutManager manager = new LinearLayoutManager(AddFamilyBodyActivity.this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        binding.recyclerRecommon.setLayoutManager(manager);

        mAdapter = SlimAdapter.create();
        //noinspection Convert2Lambda
        mAdapter.register(R.layout.item_family_relative, new SlimInjector<PhoneDto>() {
            @Override
            public void onInject(@NotNull PhoneDto data, @NotNull IViewInjector injector) {
                injector.text(R.id.tvModuleRelative, StringHelper.returnRelativeStr(data.getName()))
                        .text(R.id.tvModuleName, data.getName())
                        .with(R.id.tvModuleSelect, view -> ((CheckBox) view).setChecked(data.isChecked()))
                        .clicked(R.id.tvModuleRelative, view -> {
                            for (PhoneDto item : phoneDtosSecond) {
                                item.setChecked(false);
                            }
                            data.setChecked(true);
                            mAdapter.notifyDataSetChanged();

                            binding.etModuleTrueName.setText(data.getName());
                            binding.etModulePhone.setText(data.getTelPhone());
                            switch (StringHelper.returnSex(data.getName())) {
                                case "女":
                                    binding.tvModuleSex.setText("女");
                                    d_sex = "2";
                                    break;
                                case "男":
                                    binding.tvModuleSex.setText("男");
                                    d_sex = "1";
                                    break;
                                default:
                            }
                        });
            }
        })
                .attachTo(binding.recyclerRecommon);
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        try {
            moduleFuncation = getIntent().getStringExtra("module_funcation");
            membersBean = (FamilyDeatilCallbackBean.DataBean.MembersBean)
                    getIntent().getSerializableExtra("module_bean");

            if ("add".equals(moduleFuncation)) {
                d_home_id = SpResourceUtil.getHomeId();
                x = getIntent().getStringExtra("module_x");
                y = getIntent().getStringExtra("module_y");

                new RxPermissions(this).request(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_CONTACTS
                ).subscribe(new RxObserver<Boolean>() {

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (!aBoolean) {
                            ToastUtil.showToast(R.string.picture_jurisdiction);
                            return;
                        }

                        PhoneUtil phoneUtil = new PhoneUtil(AddFamilyBodyActivity.this);
                        List<PhoneDto> phoneDtos = phoneUtil.getPhone();
                        for (PhoneDto phoneDto : phoneDtos) {
                            if (StringHelper.isRelative(phoneDto.getName())) {
                                phoneDtosSecond.add(phoneDto);
                            }
                        }
                        binding.llModuleRelative.setVisibility(phoneDtosSecond.isEmpty() ? View.GONE : View.VISIBLE);

                        mAdapter.updateData(phoneDtosSecond);
                    }

                });
            } else if ("look".equals(moduleFuncation)) {
                d_head_pic = membersBean.getD_head_pic();
                d_id = membersBean.getD_id() + "";
                d_home_id = membersBean.getD_home_id() + "";
                x = membersBean.getD_position_x() + "";
                y = membersBean.getD_position_y() + "";
                d_user_id = membersBean.getD_user_id() + "";
                d_birthday_type = membersBean.getD_birthday_type() + "";
                d_birthday = membersBean.getD_birthday() + "";
                d_birthday_str = membersBean.getD_birthday_str();
                d_name = membersBean.getD_name();
                d_sex = membersBean.getD_sex() + "";
                d_phone = membersBean.getD_phone();
                d_pic_upload = membersBean.getD_pic_upload() + "";

                binding.setBean(membersBean);

                String str = TimeUtil.ChatToTimeStr(membersBean.getD_birthday());
                if (2 != membersBean.getD_birthday_type()) {
                    if (!TextUtils.isEmpty(str))
                        binding.tvModuleSelectDay.setText(TimeUtil.ChatToTimeStr(membersBean.getD_birthday()) + "(阳历)");
                } else {
                    if (!TextUtils.isEmpty(str))
                        binding.tvModuleSelectDay.setText(TimeUtil.ChatToTimeStr(membersBean.getD_birthday()) + "(阴历)");
                }

                if (!TextUtils.isEmpty(membersBean.getD_head_pic())) {
                    GlideUtil.setCircleMethod(AddFamilyBodyActivity.this, membersBean.getD_head_pic(), binding.ivModuleHead);
                }

                switch (membersBean.getD_sex()) {
                    case 1:
                        binding.tvModuleSex.setText("男");
                        break;
                    case 2:
                        binding.tvModuleSex.setText("女");
                        break;
                    default:
                }
                switch (membersBean.getD_pic_upload()) {
                    case 1:
                        isOpen = false;
                        binding.ivModuleChange.setImageResource(R.drawable.icon_pwd_open);
                        binding.tvModuleStatus.setText("已开启");
                        break;
                    case 0:
                        isOpen = true;
                        binding.ivModuleChange.setImageResource(R.drawable.icon_pwd_close);
                        binding.tvModuleStatus.setText("已关闭");
                        break;
                }

                if (TextUtils.equals("父亲", membersBean.getD_relation())
                        || TextUtils.equals("母亲", membersBean.getD_relation())) {
                    new RxPermissions(this).request(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_CONTACTS
                    ).subscribe(new RxObserver<Boolean>() {
                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (!aBoolean) {
                                ToastUtil.showToast(R.string.picture_jurisdiction);
                                return;
                            }

                            PhoneUtil phoneUtil = new PhoneUtil(AddFamilyBodyActivity.this);
                            List<PhoneDto> phoneDtos = phoneUtil.getPhone();
                            for (PhoneDto phoneDto : phoneDtos) {
                                if (StringHelper.isParent(phoneDto.getName())) {
                                    phoneDtosSecond.add(phoneDto);
                                }
                            }
                            binding.llModuleRelative.setVisibility(phoneDtosSecond.isEmpty() ? View.GONE : View.VISIBLE);

                            mAdapter.updateData(phoneDtosSecond);
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        binding.rvModuleLeft.setOnClickListener(this);
        binding.tvModuleRight.setOnClickListener(this);
        binding.tvModuleSelect.setOnClickListener(this);
        binding.tvModuleOk.setOnClickListener(this);
        binding.tvModuleSelectDay.setOnClickListener(this);
        binding.tvModuleSex.setOnClickListener(this);
        binding.ivModuleChange.setOnClickListener(this);
        binding.ivModuleHead.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            ArrayList<LocalMedia> selectList = (ArrayList<LocalMedia>) PictureSelector.obtainMultipleResult(data);
            String capath = selectList.get(0).getCompressPath();
            GlideUtil.setCircleMethod(AddFamilyBodyActivity.this, capath, binding.ivModuleHead);
            updateHead(new File(capath));
        } else if (requestCode == REQUEST_CODE) {
            String[] contacts = getPhoneContacts(data);
            binding.etModuleTrueName.setText(contacts[0]);
            binding.etModulePhone.setText(contacts[1]);
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivModuleHead:
                PictureSelector.create(AddFamilyBodyActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .previewImage(true)
                        .isCamera(true)
                        .imageFormat(PictureMimeType.PNG)
                        .isZoomAnim(true)
                        .compress(true)
                        .glideOverride(160, 160)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .hideBottomControls(true)
                        .compressSavePath(getCacheDir().getAbsolutePath())
                        .freeStyleCropEnabled(false)
                        .showCropFrame(true)
                        .showCropGrid(true)
                        .isGif(false)
                        .openClickSound(false)
                        .previewEggs(true)
                        .minimumCompressSize(100)
                        .isDragFrame(false)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.ivModuleChange:
                if (isOpen) {
                    isOpen = false;
                    binding.ivModuleChange.setImageResource(R.drawable.icon_pwd_open);
                    binding.tvModuleStatus.setText("已开启");
                    d_pic_upload = "1";
                } else {
                    isOpen = true;
                    binding.ivModuleChange.setImageResource(R.drawable.icon_pwd_close);
                    binding.tvModuleStatus.setText("已关闭");
                    d_pic_upload = "0";
                }
                break;
            case R.id.tvModuleSex:
                SelectSexDialog dialog = new SelectSexDialog(this);
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        d_sex = "2";
                        binding.tvModuleSex.setText("女");
                    }

                    @Override
                    public void onCloseClick() {
                        d_sex = "1";
                        binding.tvModuleSex.setText("男");
                    }
                });
                break;
            case R.id.tvModuleOk:
                d_name = binding.etModuleTrueName.getText().toString().trim();
                d_phone = binding.etModulePhone.getText().toString();
                d_relation = binding.etModuleRelation.getText().toString().trim();

                if (TextUtils.isEmpty(d_name)) {
                    ToastUtil.showToast("请输入成员名称");
                    return;
                }

                if (TextUtils.isEmpty(x) || TextUtils.isEmpty(y)) {
                    ToastUtil.showToast("请选择家庭成员关系");
                    return;
                }

                if (TextUtils.isEmpty(d_home_id)) {
                    return;
                }

                if ("add".equals(moduleFuncation)) {
                    UpdateStatus bean = new UpdateStatus();
                    bean.setStatus("1");
                    bean.setFirst("");
                    bean.setSecond("");
                    bean.setThird("");
                    bean.setForth("");
                    updateStatusDao.insert(bean);

                    postHomeCreateUser();
                } else if ("look".equals(moduleFuncation)) {
                    UpdateStatus bean = new UpdateStatus();
                    bean.setStatus("1");
                    bean.setFirst("");
                    bean.setSecond("");
                    bean.setThird("");
                    bean.setForth("");
                    updateStatusDao.insert(bean);

                    postHomeEditor();
                } else if ("edit".equals(moduleFuncation)) {
                    if (TextUtils.isEmpty(d_phone)) {
                        ToastUtil.showToast("请输入手机号");
                    } else {
                        UpdateStatus bean = new UpdateStatus();
                        bean.setStatus("1");
                        bean.setFirst("");
                        bean.setSecond("");
                        bean.setThird("");
                        bean.setForth("");
                        updateStatusDao.insert(bean);

                        postHomeEditor();
                    }
                }
                break;
            case R.id.rvModuleLeft:
                finish();
                break;
            case R.id.tvModuleRight:
                ArriveDialog arriveDialog = new ArriveDialog(this);
                arriveDialog.show();
                arriveDialog.setOnBHClickListener(position -> {
                    RefreshMessageEvent event = new RefreshMessageEvent();
                    event.setType("main");
                    event.setId(position + "");
                    EventBus.getDefault().post(event);
                    ActivityStack.getScreenManager().popAllActivityExceptOne(MainActivity.class);
                });
                break;
            case R.id.tvModuleSelect:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.tvModuleSelectDay:
                Calendar calendar = Calendar.getInstance();
                if (!TextUtils.isEmpty(d_birthday)
                        && Long.parseLong(d_birthday) > 0
                ) {
                    String dateStr = TimeHelper.getInstance()
                            .getFormatedDateTime(
                                    "yyyy-MM-dd",
                                    Long.parseLong(d_birthday)
                            );

                    try {
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = sdf.parse(dateStr);
                        calendar.setTime(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                DialogGLC mDialog = new DialogGLC(
                        AddFamilyBodyActivity.this,
                        !TextUtils.equals("2", d_birthday_type)
                );
                mDialog.show();
                if (TextUtils.equals("2", d_birthday_type)) {
                    mDialog.initCalendar(
                            new ChineseCalendar(true,
                                    calendar.get(Calendar.YEAR),
                                    calendar.get(Calendar.MONTH) + 1,
                                    calendar.get(Calendar.DAY_OF_MONTH)));
                } else {
                    mDialog.initCalendar(calendar);
                }
                mDialog.setOnDataSelectListener((yangData, yinData, index) -> {
                    switch (index) {
                        case 0:
                            d_birthday_type = "1";
                            d_birthday = TimeUtil.timeToStr(yangData);
                            d_birthday_str = yangData;
                            binding.tvModuleSelectDay.setText(yangData + "(阳历)");
                            break;
                        case 1:
                            d_birthday_type = "2";
                            d_birthday = TimeUtil.timeToStr(yinData);
                            d_birthday_str = yinData;
                            binding.tvModuleSelectDay.setText(yinData + "(阴历)");
                            break;
                        default:
                    }
                });
                break;
        }
    }

    /**
     * 添加家庭成员
     */
    public void postHomeCreateUser() {
        HTTPAPI.getInstance().postHomeCreateUser(d_relation, x, y, d_home_id, d_birthday_type, d_head_pic,
                d_birthday_str, d_name, d_birthday, d_alive, d_phone, d_sex, d_pic_upload, new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (!StringUtil.isFail(s)) {
                            StringUtil.showFail(AddFamilyBodyActivity.this, s);
                        } else {
                            final AddFamilyCallbackBean bean = GsonUtil.GsonToBean(s, AddFamilyCallbackBean.class);
                            d_id = bean.getData().getD_id();

                            RefreshMessageEvent event = new RefreshMessageEvent();
                            event.setType("refresh");
                            EventBus.getDefault().post(event);

                            inviteDialog(d_id);
                        }
                    }
                });
    }

    public void inviteDialog(final String d_id) {
        ShareFamilyFullDialog okDialog = new ShareFamilyFullDialog(this);
        okDialog.show();
        okDialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onConfirmClick() {
                checkPhone(d_phone, d_id);
            }

            @Override
            public void onCloseClick() {
                finish();
            }
        });
    }

    /**
     * 判断手机号弹窗
     */
    public void checkPhone(String phone, String d_id) {
        if (TextUtils.isEmpty(phone)) {
            AddCompleteDialog dialog = new AddCompleteDialog(this);
            dialog.show();
            dialog.setOnBHClickListener(new OnBHClickListener() {
                @Override
                public void onConfirmClick() {
                    moduleFuncation = "edit";
                    binding.llModuleRelative.setVisibility(View.GONE);
                    binding.tvModuleOk.setText("确认完善，去分享");
                }

                @Override
                public void onCloseClick() {
                    finish();
                }
            });

        } else {
            startInvita(d_id);
        }
    }

    public void startInvita(String id) {
        HTTPAPI.getInstance().startInvita(id, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(AddFamilyBodyActivity.this, s);
                } else {
                    InviteCallbackBean inner = GsonUtil.GsonToBean(s, InviteCallbackBean.class);
                    String htmlUrl = "http://home.zzwisdom.com/demo/index/share/invite_id/" + inner.getData().getInvite_id();

                    ShareDialog dialog = new ShareDialog(AddFamilyBodyActivity.this, "invite");
                    dialog.show();
                    dialog.setOnShareStypeClickListener(style -> {
                        UMWeb web = new UMWeb(htmlUrl);
                        web.setTitle("邀请" + d_name + "进入家");
                        web.setDescription("邀请家庭成员");
                        web.setThumb(new UMImage(AddFamilyBodyActivity.this, R.mipmap.ic_launcher));

                        switch (style) {
                            case "Wx":
                                new ShareAction(AddFamilyBodyActivity.this)
                                        .setPlatform(SHARE_MEDIA.WEIXIN)
                                        .withText("河南传家宝")
                                        .withMedia(web)
                                        .setCallback(new UMShareListenerExt() {
                                            @Override
                                            public void onResult(SHARE_MEDIA share_media) {
                                                finish();
                                            }
                                        })
                                        .share();
                                break;
                            case "QQ":
                                new ShareAction(AddFamilyBodyActivity.this)
                                        .setPlatform(SHARE_MEDIA.QQ)
                                        .withText("河南传家宝")
                                        .withMedia(web)
                                        .setCallback(new UMShareListenerExt() {
                                            @Override
                                            public void onResult(SHARE_MEDIA share_media) {
                                                finish();
                                            }
                                        })
                                        .share();
                                break;
                            case "cancel":
                                finish();
                                break;
                        }
                    });
                }
            }
        });
    }

    /**
     * 编辑家庭成员
     */
    public void postHomeEditor() {
        HTTPAPI.getInstance().postHomeEditor(d_id, d_relation, x, y, d_home_id, d_birthday_type, d_head_pic,
                d_birthday_str, d_name, d_birthday, d_alive, d_phone, d_sex, d_pic_upload, new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (!StringUtil.isFail(s)) {
                            StringUtil.showFail(AddFamilyBodyActivity.this, s);
                        } else {
                            RefreshMessageEvent event = new RefreshMessageEvent();
                            event.setType("refresh");
                            EventBus.getDefault().post(event);

                            if ("edit".equals(moduleFuncation)) {
                                startInvita(d_id);
                            } else if ("look".equals(moduleFuncation)
                                    && TextUtils.isEmpty(membersBean.getD_name())) {
                                inviteDialog(d_id);
                            } else {
                                ToastUtil.showToast("编辑成功");
                                finish();
                            }
                        }
                    }
                });
    }

    private String[] getPhoneContacts(Intent data) {
        String[] contact = {"", ""};
        if (data == null) return contact;
        Uri contactData = data.getData();
        if (contactData == null) return contact;

        String[] projection = new String[]{
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
        };
        @SuppressLint("Recycle")
        Cursor cursor = getContentResolver().query(contactData, projection, null, null, null);

        if (cursor == null) return contact;
        cursor.moveToFirst();
        int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

        String mName = cursor.getString(nameIndex);      //联系人姓名
        String mNumber = cursor.getString(numberIndex);  //联系人号码

        contact[0] = mName;
        contact[1] = mNumber.replace("-", "").replace(" ", "");

        cursor.close();
        return contact;
    }

    public void updateHead(File file) {
        HTTPAPI.getInstance().updateHead(file, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(AddFamilyBodyActivity.this, s);
                } else {
                    UpdateHeadCallBackBean bean = GsonUtil.GsonToBean(s, UpdateHeadCallBackBean.class);
                    d_head_pic = bean.getData();
                }
            }
        });
    }

}
